package com.xuecheng.media.service.jobhandler;

import com.xuecheng.base.utils.Mp4VideoUtil;
import com.xuecheng.media.model.po.MediaProcess;
import com.xuecheng.media.service.MediaFileProcessService;
import com.xuecheng.media.service.MediaFileService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class VideoTask {

    @Autowired
    private MediaFileProcessService mediaFileProcessService;

    @Autowired
    private MediaFileService mediaFileService;

    //ffmpeg的路径
    @Value("${videoprocess.ffmpegpath}")
    String ffmpeg_path;

    /**
     * 视频处理任务
     */
    @XxlJob("videoJobHandler")
    public void shardingJobHandler() throws Exception {

        // 分片参数
        int shardIndex = XxlJobHelper.getShardIndex();
        int shardTotal = XxlJobHelper.getShardTotal();


        XxlJobHelper.log("分片参数：当前分片序号 = {}, 总分片数 = {}", shardIndex, shardTotal);

        //确定cpu的核心数
        int processors = Runtime.getRuntime().availableProcessors();
        //查询待处理任务
        List<MediaProcess> mediaProcessList = mediaFileProcessService.getMediaProcessList(shardIndex, shardTotal, processors);
        //任务数量
        int size = mediaProcessList.size();
        log.debug("取出待处理视频任务{}条", size);
        if (size <= 0) {
            return;
        }
        //创建一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(size);
        //使用的计数器
        CountDownLatch countDownLatch = new CountDownLatch(size);
        mediaProcessList.forEach(mediaProcess -> {
            //将任务放到线程池
            executorService.execute(() -> {
                try {
                    //执行任务逻辑
                    //获取任务id
                    Long id = mediaProcess.getId();
                    //开启任务---开启乐观锁
                    boolean b = mediaFileProcessService.startTask(id);
                    if (!b) {
                        log.debug("抢占任务失败，任务id:{}", id);
                        return;
                    }
                    log.debug("开始执行任务:{}", mediaProcess);
                    //执行视频转码

                    //拿到下载文件的参数
                    String bucket = mediaProcess.getBucket();
                    String filePath = mediaProcess.getFilePath();

                    //文件id就是md5
                    String fileId = mediaProcess.getFileId();
                    //---需要下载minio文件到本地
                    File file = mediaFileService.downloadFileFromMinIO(bucket, filePath);
                    if (file == null) {
                        log.debug("下载视频出错，任务id：{}，bucket：{}，filePath：{}", id, bucket, filePath);
                        //保存任务失败的结果
                        mediaFileProcessService.saveProcessFinishStatus(id, "3", fileId, null, "下载视频到本地失败");
                        return;
                    }
                    //下载成功
                    //源avi视频的路径
                    String video_path = file.getAbsolutePath();
                    //转换后mp4文件的名称
                    String mp4_name = fileId + ".mp4";
                    //转换后mp4文件的路径
                    //创建一个临时文件
                    File tempFile = null;
                    try {
                        tempFile = File.createTempFile("mp4", ".mp4");
                    } catch (IOException e) {
                        log.debug("创建临时文件异常，{}", e.getMessage());
                        mediaFileProcessService.saveProcessFinishStatus(id, "3", fileId, null, "创建临时文件失败");
                        return;
                    }
                    String mp4_path = tempFile.getAbsolutePath();
                    //创建工具类对象
                    Mp4VideoUtil videoUtil = new Mp4VideoUtil(ffmpeg_path, video_path, mp4_name, mp4_path);
                    //开始视频转换，成功将返回success,失败则返回原因
                    String result = videoUtil.generateMp4();
                    if (!result.equals("success")) {
                        log.debug("视频转码错误，原因；{}，bucket:{},objectName:{}", result, bucket, filePath);
                        mediaFileProcessService.saveProcessFinishStatus(id, "3", fileId, null, result);
                    }
                    //上传视频到minio
                    boolean b1 = mediaFileService.addMediaFilesToMinIO(mp4_path, "video/mp4", bucket, filePath);
                    if (!b1) {
                        log.debug("上传MP4到minio失败，taskId:{},bucket:{},objectName:{}", id, bucket, filePath);
                        mediaFileProcessService.saveProcessFinishStatus(id, "2", fileId, null, "上传MP4到minio失败");
                        return;
                    }
                    //拼接MP4文件的url
                    String url = getFilePath(fileId, ".mp4");
                    //保存任务处理结果为成功
                    mediaFileProcessService.saveProcessFinishStatus(id, "2", fileId, url, "");

                } finally {
                    //计算器减一
                    countDownLatch.countDown();
                }


            });
        });

        //阻塞,给一个充裕的超时时间,防止无限等待，到达超时时间还没有处理完成则结束任务
        countDownLatch.await(30, TimeUnit.MINUTES);

    }

    private String getFilePath(String fileMd5, String fileExt) {
        return fileMd5.substring(0, 1) + "/" + fileMd5.substring(1, 2) + "/" + fileMd5 + "/" + fileMd5 + fileExt;
    }

}
